package hotel.quartz.oversea.job.base;

import hotel.base.oversea.constant.CallbackConstants;
import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.constant.CommonUrlConstants;
import hotel.base.oversea.constant.enums.MessageEnums;
import hotel.base.oversea.utils.*;
import hotel.quartz.oversea.config.service.RedisService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;


@Slf4j
public class SetCommonBaseJob implements BaseJob {
    private String timestamp = "Bmgicuj"+String.valueOf(System.currentTimeMillis())+ StringUtil.getFourRandom();

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private RedisService redisService;

    public static void main(String[] args) {
        String now = "2020-12-12 23:59:00";
        String min = now.split(" ")[1].split(":")[1];
        String Hour = now.split(" ")[1].split(":")[0];
        if("23:59".equals(Hour+":"+min)){
            System.out.printf("=="+now);
        }
    }

    /**
     * //该定时器调整cron时间为45 59 23 * * ?-》要为第45秒执行--》不能还没到00点提前1分钟就改变days
     *
     * @param jobExecutionContext
     */
    @Override
    @SneakyThrows
    public void execute(JobExecutionContext jobExecutionContext) {
        String now = DateUtil.getCurrTime();
        String min = now.split(" ")[1].split(":")[1];
        String Hour = now.split(" ")[1].split(":")[0];

        log.info("Set Common Base Job {} >>>>>>>> 定点处理公共设置 执行时间: {}", timestamp, now);

        String callbackDateMaps=  "23:59";
        if(callbackDateMaps.contains(Hour+":"+min)){
            String mapsStr = (String)redisService.get("callback_goods_info_disdaysmap");
            if(!ObjectUtils.isEmpty(mapsStr)){
                redisService.setUnit("callback_goods_info_disdaysmap", mapsStr,1L,TimeUnit.MINUTES);
                log.info("设置 callbackDateMaps callback_goods_info_disdaysmap={}",redisService.get("callback_goods_info_disdaysmap"));
            }
        }

        if(null != redisService.get("MtCbGoodsPriceRedisRemoveJob_sub_one_days_open")){
            String comparePriceRemove=  "23:59";
            if(null != comparePriceRemove && comparePriceRemove.contains(Hour+":"+min)){
                redisService.setUnit("MtCbGoodsPriceRedisRemoveJob_sub_one_days",1,6L,TimeUnit.HOURS);
            }
        }

        if(null == redisService.get("set_swmt_update_cancel_close_at_time_close")){
            String compareCancel=  "23:59";
            if(null != redisService.get("set_swmt_update_cancel_close_at_time")){
                compareCancel =(String) redisService.get("set_swmt_update_cancel_close_at_time");
            }
            if(null != compareCancel && compareCancel.contains(Hour+":"+min)){
                String t = "120";
                if(null != redisService.get("set_swmt_update_cancel_close_at_time_hours")){
                    t = (String) redisService.get("set_swmt_update_cancel_close_at_time_hours");
                }
                redisService.setUnit("PartTimeSwitchsPopQueueFailureGoodsJob_cancel_close",1,Long.valueOf(t), TimeUnit.MINUTES);
                SendUtils.dingMsgNotLog("[JOB-SET-CANCEL]携程美团基础配置 ", DateUtil.getCurrTime()+" 当前往后关闭'更新取消规则'"+t+"分钟", MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
            }
        }

        /**
         * qyy 20210311
         * 1、主动查询价格0-2点关闭，异步价格全天候开启；
         *    主动房态定时器全天候开启，异步房态0-2点关闭；
         * 2、0-2点不载入新一天价格房态
         *
         * 【异步】
         *  set_swmt_callback_price_close_at_time--》 value = not --> 异步价格全天候
         *  set_swmt_callback_status_close_at_time--》null --> 异步房态0-2点关闭
         */

        ////////////////////////////////////////////////  异步 价格 房态  start //////////////////////////////////////////////
        if(null == redisService.get("set_swmt_callback_price_close_at_time_close")){
            String comparePrice=  "23:59";
            if(null != redisService.get("set_swmt_callback_price_close_at_time")){
                comparePrice =(String) redisService.get("set_swmt_callback_price_close_at_time");
            }
            if(null != comparePrice && comparePrice.contains(Hour+":"+min)){
                String t = "60";
                if(null != redisService.get("set_swmt_callback_price_close_at_time_hours")){
                    t = (String) redisService.get("set_swmt_callback_price_close_at_time_hours");
                }
                redisService.setUnit(CallbackConstants.CLOSE_MT_CB_PRICE,1,Long.valueOf(t), TimeUnit.MINUTES);
                SendUtils.dingMsgNotLog("[JOB-SET-PRICE]携程美团基础配置 ", DateUtil.getCurrTime()+" 当前往后关闭价格异步通道"+t+"分钟", MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
            }
        }
        if(null == redisService.get("set_swmt_callback_status_close_at_time_close")){
            String compareStatus=  "23:59";
            if(null != redisService.get("set_swmt_callback_status_close_at_time")){
                compareStatus =(String) redisService.get("set_swmt_callback_status_close_at_time");
            }
            if(null != compareStatus && compareStatus.contains(Hour+":"+min)){
                String t = "60";
                if(null != redisService.get("set_swmt_callback_status_close_at_time_hours")){
                    t = (String) redisService.get("set_swmt_callback_status_close_at_time_hours");
                }
                redisService.setUnit(CallbackConstants.CLOSE_MT_CB_STATUS,1,Long.valueOf(t), TimeUnit.MINUTES);
                SendUtils.dingMsgNotLog("[JOB-SET-STATUS]携程美团基础配置 ", DateUtil.getCurrTime()+" 当前往后关闭'房态'异步通道"+t+"分钟", MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
            }
        }
        ////////////////////////////////////////////////  异步 价格 房态  end //////////////////////////////////////////////


        //////////////////////////////////////  不载入新一天  start ////////////////////////////
        //该定时器调整cron时间为45 59 23 * * ?--》要为第45秒执行--》不能还没到00点提前1分钟就改变days
        if(null != redisService.get("mtsw_job_status_price_not_load_new_day_hour_time_open_condition")){
            String compareNotLoadTime=  "23:59";
            if(null != redisService.get("mtsw_job_status_price_not_load_new_day_hour_time")){
                //不载入新一天执行时间点
                compareNotLoadTime = (String)redisService.get("mtsw_job_status_price_not_load_new_day_hour_time");//"23:59"
            }
            Integer compareNotLoadTimeCount=  2;
            if(null != redisService.get("mtsw_job_status_price_not_load_new_day_hour_time_count")){
                //不载入新一天执行时间点
                compareNotLoadTimeCount = (Integer) redisService.get("mtsw_job_status_price_not_load_new_day_hour_time_count");//2
            }
            if(null != compareNotLoadTime && compareNotLoadTime.contains(Hour+":"+min)){
                log.info("符合不载入新的一天的时间段notLoadNewDayTime：{},往后推compareNotLoadTimeCount={}",compareNotLoadTime,compareNotLoadTimeCount);
                Integer daysForJob = getDaysCommonBaseSetForJob();//不载入新的一天 dyasForJob 减 1
                Integer redisDays = Integer.valueOf((String)redisService.get(CallbackConstants.SWMT_PRICE_STATUS_DAYS));
                if(null == redisService.get(CallbackConstants.SWMT_PRICE_STATUS_DAYS) ||  new BigDecimal(daysForJob).compareTo(new BigDecimal(redisDays))!=0){
                    log.info("符合不载入新的一天的时间段,设置缓存为daysForJob：{}",daysForJob);
                    SendUtils.dingMsgNotLog("[SW-JOB-BASE-getDaysCommonBaseSet]价格房态不载入新一天", DateUtil.getCurrTime()+" 当前往后推"+compareNotLoadTimeCount+"小时，不载入新的一天", MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
                    //主动查询的set的是-1后的值
                    redisService.setUnit(CallbackConstants.SWMT_PRICE_STATUS_DAYS,String.valueOf(daysForJob),Long.valueOf(compareNotLoadTimeCount),TimeUnit.HOURS);//设置失效时间
                    //异步通道的要再-1
                    redisService.setUnit(CallbackConstants.SWMT_PRICE_STATUS_DAYS_CALLBACK,String.valueOf(daysForJob-1),Long.valueOf(compareNotLoadTimeCount),TimeUnit.HOURS);//设置失效时间
                }
            }
        }
        //////////////////////////////////////  不载入新一天  end ////////////////////////////




        log.info("Set Common Base Job {} >>>>>>>> 定点处理公共设置 结束时间: {},{}",timestamp, DateUtil.getCurrTime());

    }

    /**
     * 用途: 美团异步通道（days要减一）
     * @return
     */
    public Integer getDaysCommonBaseSetForJob() {
        String days = (String)redisService.get(CallbackConstants.SWMT_PRICE_STATUS_DAYS_JOB);
        if(ObjectUtils.isEmpty(days)){
            Result result = RestTemplateUtils.get(CommonUrlConstants.ADMIN_HOST+"/sysCommonBase/getLikeId?id="+ CallbackConstants.SWMT_PRICE_STATUS_DAYS,null,restTemplate);
            if(result.getCode() == CommonConstants.SUCCESS && !ObjectUtils.isEmpty(result.getData())){
                days = (String)result.getData();
                redisService.set(CallbackConstants.SWMT_PRICE_STATUS_DAYS_JOB,String.valueOf(Integer.valueOf(days)-1));
                return Integer.valueOf(days)-1;//减一
            }else{
                SendUtils.dingMsgNotLog("基础配置定时器-价格job获取基础配置days异常请排查", DateUtil.getCurrTime()+" 当前设置默认值价格房态查询3天 result="+ GsonUtils.GsonString(result), MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
                redisService.set(CallbackConstants.SWMT_PRICE_STATUS_DAYS_JOB,"2");
                return 3-1;//有异常默认3天并推送钉钉
            }
        }else{
            return Integer.valueOf(days);
        }
    }


}
